package com.shjy.driver.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpFileUpTool {
	private static final String BOUNDARYSTR = "XMKSSS***********";
	private static final String BOUNDARY = "--" + BOUNDARYSTR + "\r\n";
	public static String post(String actionUrl, Map<String, String> params,
			Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		StringBuilder sb2 = new StringBuilder();

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(30 * 1000); 
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false); 
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		//conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(conn
				.getOutputStream());
		outStream.write(sb.toString().getBytes());
		InputStream in = null;
		
		if (files != null){
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1
						.append("Content-Disposition: form-data; name=\"img\"; filename=\""
								+ file.getKey() + "\"" + LINEND);
				//sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
				sb1.append("Content-Type: image/png" + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
			}
			try{
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
				outStream.write(end_data);
				outStream.flush();
		
				
				int res = conn.getResponseCode();
				//if (res == 200) {
					in = conn.getInputStream();
//					int ch;
//					
//					while ((ch = in.read()) != -1) {
//						sb2.append((char) ch);
//					}
					BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8"));  
		            String line = "";  
		            
		            for (line = br.readLine(); line != null; line = br.readLine()) {  
		            	sb2.append(line);
		            }  
				//}
				outStream.close();
				conn.disconnect();
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		return sb2.toString();
	}
	
	 public static String upload(String actionUrl,File f)
	    {
	        try
	        {
	            URL url = new URL(actionUrl);
	            
	            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
	            //上传图片的一些参数设置
	            uc
	                    .setRequestProperty(
	                            "Accept",
	                            "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
	            uc.setRequestProperty("Accept-Language", "zh-cn");
	            uc
	                    .setRequestProperty("Content-type",
	                            "multipart/form-data;   boundary=---------------------------7d318fd100112");
	            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");
	            uc
	                    .setRequestProperty("User-Agent",
	                            "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
	            uc.setRequestProperty("Connection", "Keep-Alive");
	            
	            uc.setRequestMethod("POST");
	            
	            uc.setDoOutput(true);
	            uc.setUseCaches(true);
	        
	            //读取文件流
	            int size = (int) f.length();
	            byte[] data = new byte[size];
	            FileInputStream fis = new FileInputStream(f);
	            OutputStream out = uc.getOutputStream();
	            fis.read(data, 0, size);
	            //写入文件名
	            out.write(f.getName().trim().getBytes());
	            //写入分隔符
	            out.write('|');
	            //写入图片流
	            out.write(data);
	            out.flush();
	            out.close();
	            fis.close();
	            
	            //读取响应数据
	            int code = uc.getResponseCode();
	            String sCurrentLine = "";
	            //存放响应结果
	            String sTotalString = "";
	            if (code == 200)
	            {
	                InputStream is = uc.getInputStream();
	                BufferedReader reader = new BufferedReader(
	                        new InputStreamReader(is));
	                while ((sCurrentLine = reader.readLine()) != null)
	                    if (sCurrentLine.length() > 0)
	                        sTotalString = sTotalString + sCurrentLine.trim();
	            }
	            else
	            {
	                sTotalString = "远程服务器连接失败,错误代码:" + code;
	            }
	            return sTotalString;
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }
	        return null;
	    }

	// 文件上传
	public static String sendFormFile(String urlString, Map<String, String> propertys, String filePath) {
		HttpURLConnection urlConnection = null;
		FileInputStream fi = null;
		OutputStream o = null;
		String result = "";

		try {
			URL url;
			url = new URL(urlString);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("POST");

			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);

			urlConnection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
			if (propertys != null)
				for (String key : propertys.keySet()) {
					urlConnection.addRequestProperty(key, propertys.get(key));
				}
			urlConnection.connect();
			BufferedOutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());

			// 表单数据
			Map<String, String> parameters = new HashMap<String, String>();
			parameters.put("guid", "61080c526d8d48099f61744f9cf89993");
			parameters.put("billId", "17");
			parameters.put("pictureId", "");
			parameters.put("fileElementId", "idCardImage");
			parameters.put("driverUuid", "46dafe880cbc49b69078de5acc7d3e41");
			//parameters.put("name", "idCardImage");
			// parameters.put("fileName", filePath);
			// Map<String, String> propertys = getHeader();
			if (parameters != null) {
				StringBuffer param = new StringBuffer();
				for (String key : parameters.keySet()) {
					param.append(BOUNDARY);
					param.append("Content-Disposition:form-data;name=\"");
					param.append(key);
					param.append("\"\r\n\r\n");
					param.append(parameters.get(key));
					param.append("\r\n");
				}
				out.write(param.toString().getBytes());
			}
			// 文件字节数据
			File file = new File(filePath);
			StringBuilder filenamesb = new StringBuilder();
			filenamesb.append(
					"Content-Disposition:form-data;Content-Type:application/octet-stream;name=\"idCardImage\";filename=\"");//image/png
			filenamesb.append(file.getName() + "\"\r\n\r\n");
			out.write(BOUNDARY.getBytes());
			out.write(filenamesb.toString().getBytes());
			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[8192000]; // 8k
			int count = 0;
			// 读取文件
			while ((count = fis.read(buffer)) != -1) {
				out.write(buffer, 0, count);
			}
			out.write("\r\n\r\n".getBytes());
			fis.close();
			out.write(("--" + BOUNDARYSTR + "--\r\n").getBytes());
			out.flush();
			out.close();

			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = "";
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println(urlString + "====" + result);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fi != null) {
					fi.close();
				}
				if (o != null) {
					o.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return result;
	}
	 
	 public static String readContentFromGet(String location) throws IOException {
			// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
			String getURL = location;
			URL getUrl = new URL(getURL);
			// 根据拼凑的URL，打开连接，URL.openConnection函数会根据URL的类型，
			// 返回不同的URLConnection子类的对象，这里URL是一个http，因此实际返回的是HttpURLConnection
			HttpURLConnection connection = (HttpURLConnection) getUrl
					.openConnection();
			// 进行连接，但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
			// 服务器
			connection.connect();
			// 取得输入流，并使用Reader读取
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
			StringBuffer sb = new StringBuffer();
			String lines;
			while ((lines = reader.readLine()) != null) {
				// lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			// 断开连接
			connection.disconnect();
			return sb.toString();
		}
}
